//
//  HAMCalendarVC.m
//  planner
//
//  Created by 함동균 on 2014. 3. 11..
//  Copyright (c) 2014년 idea. All rights reserved.
//

#import "xIdeaCalendarVC.h"

@interface xIdeaCalendarViewController ()
@property (weak, nonatomic) IBOutlet UINavigationItem *navigationTitle;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *yearViewButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *addTaskButton;
@property (strong, nonatomic) UIBarButtonItem *searchButton;
@property (weak, nonatomic) IBOutlet UIImageView *headerView;
@property (weak, nonatomic) IBOutlet UILabel *wednesdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *tuesdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *mondayLabel;
@property (weak, nonatomic) IBOutlet UILabel *sundayLabel;
@property (weak, nonatomic) IBOutlet UILabel *thursdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *fridayLabel;
@property (weak, nonatomic) IBOutlet UILabel *saturdayLable;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenSundayMonday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenMondayTuesday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenTuesdayWednesday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenWednesdayThursday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenThursdayFriday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *xAlignBetweenFridaySaturday;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarViewWidth;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *dateLabels;

@end

@implementation xIdeaCalendarViewController
@synthesize year = _year;
@synthesize month = _month;

#pragma mark Property setter and getter
- (NSNumber *)year
{
    if (!_year) {
        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        NSDateComponents *dateComponents = [gregorianCalendar components:units
                                                                fromDate:[NSDate date]];
        _year = [NSNumber numberWithInteger:dateComponents.year];
    }
    return _year;
}

- (void)setYear:(NSNumber *)year
{
    _year = year;
    [self redrawMonthGrid];
}

- (NSNumber *)month
{
    if (!_month) {
        NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        NSDateComponents *dateComponents = [gregorianCalendar components:units
                                                                fromDate:[NSDate date]];
        _month = [NSNumber numberWithInteger:dateComponents.month];
    }
    return _month;
}

- (void)setMonth:(NSNumber *)month
{
    _month = month;
    [self redrawMonthGrid];
}

#pragma mark View controller lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.tabBarName = TAB_BAR_CALENDAR;
    
    // Add Serach Button
    self.searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch
                                                                      target:self
                                                                      action:@selector(searchTask:)];
    NSMutableArray *rightBarItems = [[NSMutableArray alloc]init];
    [rightBarItems addObjectsFromArray:self.navigationItem.rightBarButtonItems];
    [rightBarItems addObject: self.searchButton];
    self.navigationItem.rightBarButtonItems = rightBarItems;
    
    // Sort IBOutletCollection
    self.dateLabels = [self.dateLabels sortedArrayUsingComparator:^NSComparisonResult(id label1, id label2) {
        if ([label1 frame].origin.y < [label2 frame].origin.y) {
            return NSOrderedAscending;
        } else if ([label1 frame].origin.y > [label2 frame].origin.y) {
            return NSOrderedDescending;
        } else {
            if ([label1 frame].origin.x < [label2 frame].origin.x) {
                return NSOrderedAscending;
            } else if ([label1 frame].origin.x > [label2 frame].origin.x) {
                return NSOrderedDescending;
            } else {
                return NSOrderedSame;
            }
        }
    }];
    
    [self redrawMonthGrid];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    float distance;
    
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        self.calendarViewWidth.constant = self.view.frame.size.width / 2.0;
        distance = self.view.frame.size.width / 14.0;
        [self.tabBarController.tabBar setTranslucent:YES];
        [self.tabBarController.tabBar setHidden:YES];
    } else {
        distance = 44;
        self.calendarViewWidth.constant = self.view.frame.size.width;
        [self.tabBarController.tabBar setTranslucent:NO];
        [self.tabBarController.tabBar setHidden:NO];
    }
    self.xAlignBetweenSundayMonday.constant = -distance;
    self.xAlignBetweenMondayTuesday.constant = -distance;
    self.xAlignBetweenTuesdayWednesday.constant = -distance;
    self.xAlignBetweenWednesdayThursday.constant = distance;
    self.xAlignBetweenThursdayFriday.constant = -distance;
    self.xAlignBetweenFridaySaturday.constant = distance;
    
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) { // iOS 7
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    } else { // iOS 6
        if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        } else {
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        }
    }
}

- (BOOL)hidesBottomBarWhenPushed {
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)prefersStatusBarHidden {
    if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return YES;
    } else {
        return NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Data update
- (void)redrawMonthGrid
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    self.navigationTitle.title = [[df monthSymbols] objectAtIndex:[self.month intValue] - 1];
    self.yearViewButton.title = [NSString stringWithFormat:@"%d", [self.year intValue]];
    
    CalendarMonth *currentCalendarMonth = [CalendarMonth setYear:self.year
                                                           month:self.month
                                          inManagedObjectContext:[self getManagedObjectContext]];
    
    for (int i=0; i<6*7; i++) {
        CalendarDay *calendarDay = (CalendarDay *)[currentCalendarMonth.days objectAtIndex:i];
        UILabel *label = [self.dateLabels objectAtIndex:i];
        label.text = [calendarDay getDateString];
    }
}

#pragma mark Theme update
- (void)updateTheme
{
    [super updateTheme];
    [self updateThemeHeader];
    [self updateThemeGrid];
}

- (void) updateThemeHeader
{
    CGSize imageSize = self.headerView.bounds.size;
    UIGraphicsBeginImageContext(imageSize);
    
    // Draw image for header
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Header Background
    CGContextSetFillColorWithColor(context, [[self getColorForProperty:HEADER_BACKGROUND_COLOR] CGColor]);
    CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
    
    // Header Line
    CGContextSetStrokeColorWithColor(context, [[self getColorForProperty:HEADER_LINE_COLOR] CGColor]);    CGContextMoveToPoint(context, 0, imageSize.height - 1.5);
    CGContextAddLineToPoint(context, imageSize.width - 1, imageSize.height - 1.5);
    CGContextStrokePath(context);
    
    // Update Image
    self.headerView.image = UIGraphicsGetImageFromCurrentImageContext();
    
    // Tidy Up
    UIGraphicsEndImageContext();
    
    [self.sundayLabel setTextColor:[self getColorForProperty:HEADER_SUNDAY_TEXT_COLOR]];
    [self.mondayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
    [self.tuesdayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
    [self.wednesdayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
    [self.thursdayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
    [self.fridayLabel setTextColor:[self getColorForProperty:HEADER_WEEKDAY_TEXT_COLOR]];
    [self.saturdayLable setTextColor:[self getColorForProperty:HEADER_SATURDAY_TEXT_COLOR]];
}

- (void)updateThemeGrid
{
    
}

#pragma mark Actions
- (IBAction)searchTask:(id)sender {
}
@end
